<template>
  <div class="div-style">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" style="margin-top: 10px;">
      <el-row>
        <el-col :span="6">
          <el-form-item label="费别" prop="chargeType">
            <el-select v-model="form.chargeType" placeholder="请选择费别" style="width: 100%;">
              <el-option v-for="dict in dictDataMap['medical_insurance_type']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="初诊标志" prop="firstVisitIndicator">
            <el-radio-group v-model="form.firstVisitIndicator">
              <el-radio v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                        :value="dict.dictValue">{{ dict.dictLabel }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <!-- <el-form-item label="医保类别" prop="insuranceType">
                                  <el-input v-model="form.insuranceType" placeholder="请输入医保类别" />
                              </el-form-item> -->
          <el-form-item label="患者医保来源">
            <el-select v-model="form.source" placeholder="请选择费别" style="width: 100%;">
              <el-option v-for="dict in dictDataMap['patient_medical_source']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否急诊" prop="isEmergency">
            <el-radio-group v-model="form.isEmergency">
              <el-radio v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                        :value="dict.dictValue">{{ dict.dictLabel }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" clearable disabled placeholder="请输入姓名"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="证件号" v-bind:prop="isNotRequired === 'N' || !isOtcOutpatient ?'idNo' : ''">
            <el-input v-model="form.idNo" clearable placeholder="请输入证件号"
                      @blur="certificateNoBlur">
              <template #prepend>
                <el-select
                  v-model="form.certificateType"
                  clearable
                  placeholder="请选择证件类型"
                  style="width: 120px"
                >
                  <el-option
                    v-for="dict in dictDataMap['certificate_type']"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <!--          <el-form-item label="出生日期" v-bind:prop="isNotRequired === 'N' || !isOtcOutpatient  ?'birthdayDate' : ''">-->
          <el-form-item label="出生日期">
            <el-date-picker v-model="form.birthdayDate" clearable type="date" value-format="YYYY-MM-DD"
                            placeholder="请选择出生日期" @change="birthdayDateChange">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="性别" v-bind:prop="isNotRequired === 'N'  || !isOtcOutpatient ?'sex' : ''">
            <el-select v-model="form.sex" placeholder="请选择性别" style="width: 100%;">
              <el-option v-for="dict in dictDataMap['sys_user_sex']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-row>
            <el-col :span="4" class="age-margin">
              <el-form-item label="年龄" v-bind:prop="isNotRequired === 'N'  || !isOtcOutpatient ?'age' : ''">
                <el-input ref="ageRef" v-model="form.age" class="age" clearable placeholder="岁">
                  <template #append>岁</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="age-margin">
              <el-form-item v-bind:prop="isNotRequired === 'N'  || !isOtcOutpatient ?'ageMonth' : ''">
                <el-input v-model="form.ageMonth" class="age" clearable placeholder="月">
                  <template #append>月</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="age-margin">
              <el-form-item v-bind:prop="isNotRequired === 'N'  || !isOtcOutpatient ?'ageDay' : ''">
                <el-input v-model="form.ageDay" class="age" clearable placeholder="天">
                  <template #append>天</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="age-margin">
              <el-form-item v-bind:prop="isNotRequired === 'N' || !isOtcOutpatient  ?'ageHours' : ''">
                <el-input v-model="form.ageHours" class="age" clearable placeholder="时">
                  <template #append>时</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="age-margin">
              <el-form-item v-bind:prop="isNotRequired === 'N'  || !isOtcOutpatient ?'ageMinutes' : ''">
                <el-input v-model="form.ageMinutes" class="age" clearable placeholder="分">
                  <template #append>分</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="age-margin">
              <el-button plain style="position: absolute;right: 0px;" type="primary" @click="resetAge">
                清空
              </el-button>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系电话" v-bind:prop="isNotRequired === 'N'  || !isOtcOutpatient ?'phone' : ''">
            <el-input v-model="form.phone" clearable placeholder="请输入联系电话"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="婚姻" prop="marriage">
            <el-select v-model="form.marriage" placeholder="请选择婚姻状态" style="width: 100%;">
              <el-option v-for="dict in dictDataMap['marriage_dict']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="民族" prop="nation">
            <el-select v-model="form.nation" placeholder="请选择民族" style="width: 100%;">
              <el-option v-for="dict in dictDataMap['nation_dict']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="国籍" prop="nationality">
            <el-select v-model="form.nationality" placeholder="请选择国籍" style="width: 100%;">
              <el-option v-for="dict in dictDataMap['nationality_dict']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="乡组" prop="countryGroup">
            <el-input v-model="form.countryGroup" clearable placeholder="请输入乡组"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="住址">
            <level-address :value="form.addressCode" style="width: 50%;"
                           @handleChange="handleChangeAddressCode"/>
            <el-input v-model="form.address" clearable placeholder="请输入住址" style="width: 50%;"
                      @clear="clear"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="籍贯" prop="nativePlace">
            <el-input v-model="form.nativePlace" clearable placeholder="请输入籍贯"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生地" prop="homePlace">
            <el-input v-model="form.homePlace" clearable placeholder="请输入出生地"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="联系人关系" prop="contactsRelation">
            <el-select v-model="form.contactsRelation" placeholder="请选择联系人关系" style="width: 100%;">
              <el-option v-for="dict in dictDataMap['relationship_dict']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系人" prop="contacts">
            <el-input v-model="form.contacts" placeholder="请输入联系人"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系人身份证" prop="contactsIdNo">
            <el-input v-model="form.contactsIdNo" clearable placeholder="请输入联系人身份证"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系人地址" prop="contactsAddress">
            <el-input v-model="form.contactsAddress" clearable placeholder="请输入联系人地址"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="联系人电话" prop="contactsPhone">
            <el-input v-model="form.contactsPhone" clearable placeholder="请输入联系人电话"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="身份" prop="identity">
            <el-select v-model="form.identity" placeholder="请选择身份" style="width: 100%;">
              <el-option v-for="dict in dictDataMap['profession_dict']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="文化程度" prop="eduLevel">
            <el-select v-model="form.eduLevel" placeholder="请选择文化程度" style="width: 100%;">
              <el-option v-for="dict in dictDataMap['education_dict']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="监护人姓名" prop="guardianName">
            <el-input v-model="form.guardianName" clearable placeholder="请输入监护人姓名"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="监护人电话" prop="guardianPhone">
            <el-input v-model="form.guardianPhone" clearable placeholder="请输入监护人电话"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否公账" prop="isPublicAccounts">
            <el-radio-group v-model="form.isPublicAccounts">
              <el-radio v-for="dict in dictDataMap['sys_yes_no']"
                        :key="dict.dictValue"
                        :value="dict.dictValue">{{
                  dict.dictLabel
                }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item v-if="form.isPublicAccounts === 'Y'" label="统一社会信用代码" label-width="120"
                        prop="unifiedSocialCreditCode">
            <el-input v-model="form.unifiedSocialCreditCode" clearable
                      placeholder="请输入统一社会信用代码"/>
          </el-form-item>
        </el-col>
      </el-row>
      <!--            <el-row>-->
      <!--                <el-col :span="24">-->
      <!--                    <el-form-item label="初步诊断" prop="aaaa">-->
      <!--                        <el-input v-model="form.aaaa" clearable disabled placeholder="请输入初步诊断" />-->
      <!--                    </el-form-item>-->
      <!--                </el-col>-->
      <!--            </el-row>-->
      <!-- <el-form-item label="医疗保险号" prop="insuranceNo">
                              <el-input v-model="form.insuranceNo" placeholder="请输入医疗保险号" />
                          </el-form-item>
                          <el-form-item label="医保就医登记流水号" prop="residenceNo">
                              <el-input v-model="form.residenceNo" placeholder="请输入医保就医登记流水号" />
                          </el-form-item> -->

      <el-button style="float: right;" type="primary" @click="submitForm">保 存</el-button>
      <el-button v-if="form.clinicType !='2'" class="mr5" style="float: right;" type="success"
                 @click="updateDoctorIdFun">完成接诊
      </el-button>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import {getClinicMaster, updateClinicMaster, updateDoctorId} from "@/api/patient/clinicMaster";
import {useUserStoreHook} from "@/store/modules/user"
import {useDictStoreHook} from "@/store/modules/dict"
import {selectConfigByCache} from "@/api/system/orgConfig.ts";

const dictStore = useDictStoreHook()
let dictDataMap = ref(dictStore.isTypeGetData('register_type', 'payment_method', 'patient_medical_source', 'sys_yes_no',
  'medical_insurance_type', 'sys_user_sex', 'marriage_dict', 'nation_dict', 'nationality_dict', 'relationship_dict',
  'profession_dict', 'education_dict', 'pay_way_dict', 'certificate_type'))
const useUserStore = useUserStoreHook()
const {proxy} = getCurrentInstance() as any
const clinicId = ref(proxy.$clinicId)
const patientId = ref(proxy.$patientId)
const emits = defineEmits(["closeLoading"])
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo
const formRef = ref()

const props = defineProps({
  // 是否来在OTC门诊  默认不是来自otc门诊
  isOtcOutpatient: {
    type: Boolean,
    default: false
  }
})

//  门诊患者基本信息不必填（身份证、性别、年龄、出生日期、联系电话、婚姻）
const isNotRequired = ref("N")
const form = ref<any>({
  recordNo: "",
  isPublicAccounts: "N",
  certificateType: "0",
  firstClinicRecord: "",
  firstOrder: "",
  firstCharge: "",
  firstExamConfirm: "",
  firstLabConfirm: "",
  firstTakeDrug: "",
  firstTakeZdrug: "",
  orgId: userInfo.orgId,
  registType: "0",
  isEmergency: "N",
  patientId: "",
  visitNo: 0,
  clinicNo: "",
  registId: "",
  name: "",
  inputCode: "",
  sex: "1",
  age: 0,
  ageMonth: 0,
  ageDay: 0,
  ageHours: 0,
  ageMinutes: 0,
  phone: "",
  address: "",
  addressCode: "",
  idNo: "",
  guardianName: "",
  guardianPhone: "",
  birthdayDate: "",
  marriage: "10",
  weight: "",
  nation: "01",
  nationality: "CN",
  nativePlace: "",
  nativePlaceCode: "",
  zipCode: "",
  homePlace: "",
  homePlaceCode: "",
  countryGroup: "",
  contactsRelation: "",
  contacts: "",
  contactsIdNo: "",
  contactsAddress: "",
  contactsPhone: "",
  identity: "",
  eduLevel: "",
  chargeType: "1",
  insuranceType: "",
  source: "1",
  clinicSource: "",
  firstVisitIndicator: "Y",
  insuranceNo: "",
  residenceNo: "",
  unitInContract: "",
  unitEin: "",
  deptId: "",
  doctorId: "",
  clinicType: "",
  clinicChage: 0,
  registDate: "",
  registOperator: "",
  registNo: "",
  acctDateTime: "",
  referralNum: 0,
  acctNo: "",
  remarks: "",
  isPhy: "",
  tripCode: "",
  healthyCode: "",
  flag: "",
  chargeFlag: "",
  unattendedDoctor: "",
  registerFlag: "",
  serialNo: "",
  readFlag: "",
  ptPayId: "",
  otpErReflFlag: "",
  mdtrtGrpType: "",
  trumFlag: "",
  relTtpFlag: "",
  // 号表id
  clinicForRegistId: ""
})
const rules = ref({
  idNo: [
    {required: true, message: "证件号不能为空", trigger: "blur"}
    // {required: true, validator: idNo, trigger: "blur"}
  ],
  isEmergency: [
    {required: true, message: "是否急诊不能为空", trigger: "blur"}
  ],
  birthdayDate: [
    {required: true, message: "出生日期不能为空", trigger: "change"}
  ],
  sex: [
    {required: true, message: "性别不能为空", trigger: "blur"}
  ],
  phone: [
    {required: true, message: "电话不能为空", trigger: "blur"}
    // {required: true, validator: phone, trigger: "blur"}
  ],
  marriage: [
    {required: true, message: "婚姻状态不能为空", trigger: "blur"}
  ],
  address: [
    {required: true, message: "住址不能为空", trigger: "blur"}
  ],
  name: [
    {required: true, message: "姓名不能为空", trigger: "blur"}
  ],
  age: [
    {required: true, validator: ageValidtor, trigger: "blur"}
  ],
  ageMonth: [
    {required: false, validator: ageValidtor, trigger: "blur"}
  ],
  ageDay: [
    {required: false, validator: ageValidtor, trigger: "blur"}
  ],
  ageHours: [
    {required: false, validator: ageValidtor, trigger: "blur"}
  ],
  ageMinutes: [
    {required: false, validator: ageValidtor, trigger: "blur"}
  ]
})

function getClinicMasterFun() {

  clinicId.value = proxy.$clinicId
  patientId.value = proxy.$patientId
  getClinicMaster(proxy.$clinicId).then((res: any) => {
    form.value = res.data
    emits("closeLoading")
  })
}


/**
 * 从门诊病历簿页面调用进来的方法
 */
function getCheckTheMedicalRecordMasterFun(clinicIdThis, patientIdThis) {
  clinicId.value = clinicIdThis
  patientId.value = patientIdThis
  getClinicMaster(clinicIdThis).then((res: any) => {
    form.value = res.data
    emits("closeLoading")
  })
}

// 身份证获取患者性别、出生年月日、年龄
function certificateNoBlur() {
  if (form.value.certificateType === "0") {
    const idNo = form.value.idNo
    // 获取性别
    const sex = proxy.$certificateNoInSex(idNo)
    form.value.sex = sex
    // 获取出生年月日
    const birthday = proxy.$certificateNoInBirthday(idNo)
    form.value.birthdayDate = birthday
    // 获取年龄 返回年月日小时对象
    const ageObj = proxy.$certificateNoInAge(birthday)
    if (ageObj) {
      form.value.age = ageObj.yStr
      form.value.ageMonth = ageObj.mStr
      form.value.ageDay = ageObj.dStr
      form.value.ageHours = ageObj.hStr
    }
  }
}


/**
 * 根据出生日期获取年龄
 */
function birthdayDateChange() {
// 获取年龄 返回年月日小时对象
  const ageObj = proxy.$certificateNoInAge(form.value.birthdayDate);
  if (ageObj) {
    form.value.age = ageObj.yStr;
    form.value.ageMonth = ageObj.mStr;
    form.value.ageDay = ageObj.dStr;
    form.value.ageHours = ageObj.hStr;
  }
}

// 年龄组清空
function resetAge() {
  form.value.age = 0
  form.value.ageMonth = 0
  form.value.ageDay = 0
  form.value.ageHours = 0
  form.value.ageMinutes = 0
}

/** 提交按钮 */
function submitForm() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        form.value.isUpdateDoctorId = "Y"
        // form.value.doctorId = userInfo.userId
        updateClinicMaster(form.value).then(_response => {
          ElMessage.success("接诊完成");
          form.value.clinicType = '2'
          // getList();
        }).finally(() => {
        });
      }
    }
  });
}

function updateDoctorIdFun() {
  form.value.isUpdateDoctorId = "Y"
  updateDoctorId(form.value).then(() => {
    ElMessage.success("接诊成功");
  })
}

// 年龄非空校验
function ageValidtor(rule, _value, callback) {
  if (isNull(form.value.age)) {
    if (!isNull(form.value.age) || !isNull(form.value.ageMonth)
      || !isNull(form.value.ageDay) || !isNull(form.value.ageHours) || !isNull(form.value.ageMinutes)) {
      formRef.value.clearValidate(['age', 'ageMonth', 'ageDay', 'ageHours', 'ageMinutes'])
      callback();
      return;
    } else {
      formRef.value.clearValidate(['ageMonth', 'ageDay', 'ageHours', 'ageMinutes'])
      callback(new Error(rule.message || "请输入年龄"));
    }
  } else {
    formRef.value.clearValidate(['age', 'ageMonth', 'ageDay', 'ageHours', 'ageMinutes'])
    callback();
    return
  }
}

function isNull(str) {
  if (str === "" || str === "0" || str === 0) {
    return true
  } else {
    return false
  }
}

function clear() {
  form.value.addressCode = ''
}

/** 省市县区点击事件 */
function handleChangeAddressCode(obj: any) {
  if (obj) {
    form.value.addressCode = obj['townlet'].value
    form.value.address = obj['economize'].label + obj['city'].label + obj['county'].label + obj['townlet'].label + form.value.address
  }
}

/**
 * 门诊患者基本信息不必填（身份证、性别、年龄、出生日期、联系电话、婚姻）
 */
function selectConfigByCacheFun() {
  // 便捷门诊可以不选诊断开药
  selectConfigByCache(userInfo.orgId, "outp.patientInfo.isNotRequired").then((res => {
    isNotRequired.value = res.data.configValue
  }))
}

selectConfigByCacheFun()
defineExpose({
  getClinicMasterFun,
  getCheckTheMedicalRecordMasterFun
})
</script>
<script lang="ts">
export default {
  name: "PatientInfo",
};
</script>
<style scoped>

:deep(.age .el-input__inner) {
  width: 35px;
}

:deep(.el-input-group__append) {
  padding: 0 5px;
  width: 40px;
}
</style>
